# coding=utf8
__author__ = 'lijian'
import lamp
from protocol.uplink.packet import *
from utils import bcdUtil
import datetime


def td_c(raw):
    if len(raw) < 5:
        return None

    bcd = bcdUtil.bcdTohex(raw)

    min = bcd[0]
    hour = bcd[1]
    day = bcd[2]
    month = bcd[3]
    year = 2000 + bcd[4]
    sec = 0

    t = datetime.datetime(year, month, day, hour, min, sec)
    return t


_fnValueDict = {
    17: "V",
    18: "A",
    19: "AP",
    20: "PF",
    21: "APP",
    22: "RP"
}


def find_history_curve(dataUnit):
    holderNo = dataUnit.PN
    bcd = dataUnit.rawData[0:5]
    bcd.insert(0,0)

    startTime=bcdUtil.decodeDateTime(bcd);

    m = dataUnit.rawData[5]
    count = dataUnit.rawData[6]

    holder = lamp.manager.findHolder(holderNo)
    if not holder:
        return False
    else:
        details = holder.findHistory(startTime, m, count)

        data = []
        data.extend(dataUnit.rawData[0:5])
        data.append(m)
        data.append(len(details))

        func = eval("lamp.Holder.encode%s" % _fnValueDict[dataUnit.FN])
        for detail in details:
            value = func(detail)
            data.extend(value)

        du = DataUnit(pn=dataUnit.PN, fn=dataUnit.FN, data=data)
        return du


def fn_17(dataUnit):
    return find_history_curve(dataUnit)


def fn_18(dataUnit):
    return find_history_curve(dataUnit)


def fn_19(dataUnit):
    return find_history_curve(dataUnit)


def fn_20(dataUnit):
    return find_history_curve(dataUnit)


def fn_21(dataUnit):
    return find_history_curve(dataUnit)


def fn_22(dataUnit):
    return find_history_curve(dataUnit)